import { Vec3 } from 'cc';
import { PageView } from 'cc';
import { UI } from 'cc';
import { find } from 'cc';
import { UITransform } from 'cc';
import { _decorator, Component, Node } from 'cc';
import UtilTool from '../tools/UtilTool';
const { ccclass, property } = _decorator;

let PAGE_DEFAULT_SCALE = 1.4 // 默认缩放比例

/**
 * 自动控制PageView里滑动时每个page页的缩放
 */
@ccclass('ScrollPageScale')
export class ScrollPageScale extends Component {

    @property(Number)
    pageScale: number = PAGE_DEFAULT_SCALE;

    @property(Number)
    defaultPageIndex: number = 0;
    
    onLoad() {
        // pageview控件Size Mode设置为: Free
        this.node.getComponent(PageView).sizeMode = PageView.SizeMode.Free
        this.node.on("scrolling", this.onScrollPageView, this);
    }

    start() {
        let pageView = this.node.getComponent(PageView)
        pageView.scrollToPage(this.defaultPageIndex,0)
        pageView.setCurrentPageIndex(this.defaultPageIndex)
    }

    onScrollPageView(event : PageView , eventType) {

        let content = find("view/content", event.node) as Node

        if(!content) {
            console.error("ScrollPageScale: can not find content node")
            return
        }

        let children = content.children

        if(children.length <= 1) return // 只有一页不需要缩放
        
        let interval = Math.abs(children[0].position.x - children[1].position.x)
        
        let centerPos = event.node.parent.getComponent(UITransform).convertToWorldSpaceAR(new Vec3(0, 0, 0))

        for(let i = 0; i < children.length; i++) {
            let child = children[i]
            let offest = Math.abs(centerPos.x - child.worldPosition.x)
            let scale = Math.max(1, 1 + (PAGE_DEFAULT_SCALE-1) * (interval-offest) / interval)
            child.scale = new Vec3(scale, scale, 1)
        }
        
    }
    
}

